package com.itheima.ydd.interceptor;

import com.itheima.ydd.commom.BaseContext;
import com.itheima.ydd.commom.UserIdContext;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 编写过滤器，实现登陆前的过滤验证
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求{}",request.getRequestURI());

        String token = request.getHeader("token");  //前台
        String xtoken = request.getHeader("x-token");  //后台

        if (xtoken == null && token == null) {
            return false;
        }

        //得到token判断当前token是否是有效的
        boolean verifyToken1 = JwtUtils.verifyToken(token);
        boolean verifyToken2 = JwtUtils.verifyToken(xtoken);

        if (!verifyToken2 && !verifyToken1) {
            response.setStatus(401);
            return false;
        }


        //前台
        //如果token有效，则从中获取到指定的值
        if(verifyToken1) {
            Claims claims = JwtUtils.getClaims(token);

            Integer userId = (Integer) claims.get("userId");
            Integer roleId = (Integer) claims.get("roleId");
            SysUser user = new SysUser();
            user.setId(userId.toString());
            if (roleId != null) {
                user.setRoleId(roleId.toString());
            }
            BaseContext.setCurrentId(user);
            UserIdContext.setCurrentId(userId.toString());

        }

        //后台
        if(verifyToken2){
            Claims claims = JwtUtils.getClaims(xtoken);

            SysUser sysUser = new SysUser();
            String userId = (String) claims.get("userId");
            String roleId = (String) claims.get("roleId");
            sysUser.setId(userId);
            sysUser.setRoleId(roleId);

            BaseContext.setCurrentId(sysUser);

            UserIdContext.setCurrentId(userId);
        }

        log.info("当前线程token有效。。。。");
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //当前线程走完后，移除用户的信息
        BaseContext.remove();
    }
}
